package com.cn.shuangzi.ad.manager;

import android.app.Activity;
import android.graphics.Point;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationNativeToBannerListener;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.OnAdClosedListener;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.util.SZXmlUtil;
import com.qq.e.ads.banner2.UnifiedBannerView;

import java.util.List;

public class AdBannerManager {
    private TTNativeExpressAd bannerAd = null;

    private Activity mActivity;
    private String mAdUnitId; //广告位
    private String scenarioId; //广告位
    private ViewGroup bannerContainer;
    private Class<?> classVip;
    private OnAdClosedListener onAdClosedListener;

    public AdBannerManager(Activity activity, ViewGroup bannerContainer) {
        this(activity, bannerContainer, null,null);
    }

    public AdBannerManager(Activity activity, ViewGroup bannerContainer, Class<?> classVip) {
        this(activity, bannerContainer, classVip,null);
    }

    public AdBannerManager(Activity activity, ViewGroup bannerContainer, Class<?> classVip, OnAdClosedListener onAdClosedListener) {
        //如果接入了Unity sdk 建议提前初始化
//        GMAdManagerHolder.initUnitySdkBanner(activity);
        mActivity = activity;
        this.classVip = classVip;
        this.bannerContainer = bannerContainer;
        this.onAdClosedListener = onAdClosedListener;
    }

    public TTNativeExpressAd getBannerAd() {
        return bannerAd;
    }
    public void loadAd(String mediaId){
        loadAd(mediaId,null,null);
    }
    public void loadAd(String mediaId,String scenarioId,MediationNativeToBannerListener listener) {
        bannerContainer.removeAllViews();

        /** 这里是简单的banner请求adSlot设置，如果需要更多的设置，可参考AdUtils.kt中bannerAdSlot函数部分。 */
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mediaId)
                .setImageAcceptedSize(ADUtil.px2dip(640), ADUtil.px2dip(100)) // 单位px
                .setMediationAdSlot(
                        new MediationAdSlot.Builder()
                                .setScenarioId(scenarioId)
                                /**
                                 * banner混出自渲染信息流时，需要提供该转换listener，将信息流自渲染素材转成view。模板类型无需处理
                                 * 如果未使用banner混出信息流功能，则无需设置MediationNativeToBannerListener。
                                 * 如要使用混出功能，可参考AdUtils.kt类中getCSJMBannerViewFromNativeAd函数部分。
                                 */
                                .setMediationNativeToBannerListener(listener)
                                .build()
                )
                .build();

        TTAdNative adNativeLoader = TTAdManagerHolder.getInstance().createAdNative(mActivity);
        adNativeLoader.loadBannerExpressAd(adSlot,new TTAdNative.NativeExpressAdListener(){
            @Override
            public void onError(int i, String s) {

                ADUtil.logError("banner显示失败:" + s);
                ADManager.getInstance().setYlhBannerAd(null);
                ADManager.getInstance().setBannerYlhErrorInfo(null);
//                ADUtil.logError("=====banner重新加载=====");
//                loadAdWithCallback(mAdUnitId,scenarioId);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                bannerAd = list.get(0);
                bannerAd.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
                    @Override
                    public void onAdDismiss() {
                        if (classVip != null && !mActivity.isFinishing()) {
                            SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
                            if(!szXmlUtil.getBoolean("isShownBannerVip")){
                                szXmlUtil.put("isShownBannerVip",true);
                                new AlertVipDialog(mActivity, classVip).show();
                            }
                        }
                        if (onAdClosedListener != null) {
                            onAdClosedListener.onAdClosed();
                        }
                    }

                    @Override
                    public void onAdClicked(View view, int i) {

                    }

                    @Override
                    public void onAdShow(View view, int i) {

                        MediationAdEcpmInfo gmAdEcpmInfo = bannerAd.getMediationManager().getShowEcpm();
                        ADUtil.logError("banner显示成功！Ecpm="+gmAdEcpmInfo);
                        if(gmAdEcpmInfo!=null) {
                            if(!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())) {
                                UnifiedBannerView unifiedBannerView = ADManager.getInstance().getYlhBannerAd();
                                YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getBannerYlhErrorInfo();
                                if (gmAdEcpmInfo != null && unifiedBannerView != null && ylhErrorInfo != null) {
                                    int ecpm = unifiedBannerView.getECPM();
                                    try {
                                        if (ecpm <= 0) {
                                            ecpm = 2 * ADConst.YUAN;
                                        }
                                        double preEcpm = Double.parseDouble(gmAdEcpmInfo.getEcpm());
                                        if(preEcpm>0) {
                                            ecpm = (int) (preEcpm + 0.5 * ADConst.YUAN);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    unifiedBannerView.sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                                    ADUtil.logError("上报优量汇Banner竞价失败：ecpm="+ecpm+"，"+ylhErrorInfo);
                                }
                            }
                        }

                        ADManager.getInstance().setYlhBannerAd(null);
                        ADManager.getInstance().setBannerYlhErrorInfo(null);
                    }

                    @Override
                    public void onRenderFail(View view, String s, int i) {

                    }

                    @Override
                    public void onRenderSuccess(View view, float v, float v1) {

                    }
                });
                showBannerAd();
            }
        });
    }


    public void destroy() {
        try {
            if (getBannerAd() != null) {
                getBannerAd().destroy();
            }
            mActivity = null;
            bannerAd = null;
            ADUtil.logError("Banner destroy成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 展示广告
     */
    public void showBannerAd() {
        ADUtil.logError("====加载成功显示banner====");
        /**
         * 加载成功才能展示
         */
        if (bannerContainer != null) {
            if (getBannerAd() != null) {
                // 在调用getBannerView之前，可以选择使用isReady进行判断，当前是否有可用广告。
                //横幅广告容器的尺寸必须至少与横幅广告一样大。如果您的容器留有内边距，实际上将会减小容器大小。如果容器无法容纳横幅广告，则横幅广告不会展示
                /**
                 * mBannerViewAd.getBannerView()一个广告对象只能调用一次，第二次为null
                 */
                View view = getBannerAd().getExpressAdView();
                if (view != null) {
                    bannerContainer.removeAllViews();
                    bannerContainer.addView(view, getSmallUnifiedBannerLayoutParams());
                }
            }
        }
    }

    private FrameLayout.LayoutParams getSmallUnifiedBannerLayoutParams() {
        int width = ADUtil.dip2px(230);
        return new FrameLayout.LayoutParams(width, Math.round(width / 6.4F));
    }
    private FrameLayout.LayoutParams getBigUnifiedBannerLayoutParams() {
        Point screenSize = new Point();
        mActivity.getWindowManager().getDefaultDisplay().getSize(screenSize);
        return new FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / 6.4F));
    }

}
